<?php

namespace app\index\controller;

use app\index\model\Moneyflow;
use app\index\model\Order;
use app\index\model\Store;
use app\index\model\Withdraw;
use app\util\Alipay;
use app\util\Utils;
use app\util\WxPay;
use think\Controller;
use think\Db;
use think\Validate;

/*
 * Api类
 */
class ApiController extends Controller
{
    /*
     * 每日审核
     */
    public function dayscheck()
    {
        $rule = [
            'page' => 'integer|egt:1',
        ];
        $msg = [
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为1',
        ];

        $all = input('post.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $page = isset($all['page']) ? $all['page'] : 1;

        $perPage = 10;
        $offset = ($page - 1) * $perPage;

        $list = Db::name('dayscheck')
            ->field('id, ordmoney, flowmoney, note, datatime')
            ->order('id desc')
            ->limit($offset, $perPage)
            ->select();
        if (count($list) > 0) {
            foreach ($list as $key => $value) {
                $list[$key]['datatime'] = date('Y-m-d', $value['datatime']);
            }
        }

        return Utils::ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 今日订单
     */
    public function today()
    {
        $rule = [
            'page' => 'integer|egt:1',
        ];
        $msg = [
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为1',
        ];

        $all = input('post.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $page = isset($all['page']) ? $all['page'] : 1;

        $perPage = 10;
        $offset = ($page - 1) * $perPage;

        $todayStart = mktime(0, 0, 0, date('m'), date('d'), date('Y'));

        $where['add_time'] = ['>=', $todayStart];
        $where['pay_money'] = ['>', 0];

        $list = Order::where($where)
            ->field('id, type, source, real_money, pay_money, status, ord_num, add_time, checkstatus')
            ->order('id desc')
            ->limit($offset, $perPage)
            ->select();
        if (count($list) > 0) {
            foreach ($list as $k => $v) {
                $id = $v['id'];
                $checkstatus = $v['checkstatus'];
                if ($checkstatus == 0) {
                    $status = $v['status'];
                    $ord_num = $v['ord_num'];

                    $check = 0;
                    $result = 0;

                    $wxPay = new WxPay();
                    $appWxResult = $wxPay->AppWxAudit($ord_num);
                    if ($appWxResult['return_code'] == 'SUCCESS' && $appWxResult['result_code'] == 'SUCCESS' && $appWxResult['trade_state'] == 'SUCCESS') {
                        $check = 1;
                    }

                    $htmlWxResult = $wxPay->H5WxAudit($ord_num);
                    if ($htmlWxResult['return_code'] == 'SUCCESS' && $htmlWxResult['result_code'] == 'SUCCESS' && $htmlWxResult['trade_state'] == 'SUCCESS') {
                        $check = 1;
                    }

                    $alipay = new Alipay();
                    $appAlipayResult = $alipay->doQuery($ord_num);
                    if ($appAlipayResult->code == 10000 && ($appAlipayResult->trade_status == 'TRADE_SUCCESS' || $appAlipayResult->trade_status == 'TRADE_FINISHED')) {
                        $check = 1;
                    }

                    if ($check == 1) {
                        if ($status > 1) {
                            $result = 1;
                        } else {
                            $result = 4;
                        }
                    } else {
                        if ($status > 1) {
                            $result = 3;
                        } else {
                            $result = 2;
                        }
                    }

                    Order::where('id', '=', $id)->update(['checkstatus' => $result]);

                    $list[$k]['checkstatus'] = $result;
                }

                $list[$k]['add_time'] = date('Y-m-d H:i:s', $list[$k]['add_time']);
            }
        }

        return Utils::ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 昨日订单
     */
    public function yesterday()
    {
        $rule = [
            'page' => 'integer|egt:1',
        ];
        $msg = [
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为1',
        ];

        $all = input('post.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $page = isset($all['page']) ? $all['page'] : 1;

        $perPage = 10;
        $offset = ($page - 1) * $perPage;

        $yesterdayStart = strtotime('-1 days', mktime(0, 0, 0, date('m'), date('d'), date('Y')));
        $yesterdayEnd = strtotime('-1 days', mktime(23, 59, 59, date('m'), date('d'), date('Y')));

        $where['pay_money'] = ['>', 0];

        $list = Order::where($where)
            ->where('add_time', '>=', $yesterdayStart)
            ->where('add_time', '<=', $yesterdayEnd)
            ->field('id, type, source, real_money, pay_money, status, ord_num, add_time, checkstatus')
            ->order('id desc')
            ->limit($offset, $perPage)
            ->select();
        if (count($list) > 0) {
            foreach ($list as $k => $v) {
                $id = $v['id'];
                $checkstatus = $v['checkstatus'];
                if ($checkstatus == 0) {
                    $status = $v['status'];
                    $ord_num = $v['ord_num'];

                    $check = 0;
                    $result = 0;

                    $wxPay = new WxPay();
                    $appWxResult = $wxPay->AppWxAudit($ord_num);
                    if ($appWxResult['return_code'] == 'SUCCESS' && $appWxResult['result_code'] == 'SUCCESS' && $appWxResult['trade_state'] == 'SUCCESS') {
                        $check = 1;
                    }

                    $htmlWxResult = $wxPay->H5WxAudit($ord_num);
                    if ($htmlWxResult['return_code'] == 'SUCCESS' && $htmlWxResult['result_code'] == 'SUCCESS' && $htmlWxResult['trade_state'] == 'SUCCESS') {
                        $check = 1;
                    }

                    $alipay = new Alipay();
                    $appAlipayResult = $alipay->doQuery($ord_num);
                    if ($appAlipayResult->code == 10000 && ($appAlipayResult->trade_status == 'TRADE_SUCCESS' || $appAlipayResult->trade_status == 'TRADE_FINISHED')) {
                        $check = 1;
                    }

                    if ($check == 1) {
                        if ($status > 1) {
                            $result = 1;
                        } else {
                            $result = 4;
                        }
                    } else {
                        if ($status > 1) {
                            $result = 3;
                        } else {
                            $result = 2;
                        }
                    }

                    Order::where('id', '=', $id)->update(['checkstatus' => $result]);

                    $list[$k]['checkstatus'] = $result;
                }

                $list[$k]['add_time'] = date('Y-m-d H:i:s', $list[$k]['add_time']);
            }
        }

        return Utils::ajaxReturn(0, '查询成功', $list);
    }

    /*
     * 全部订单
     */
    public function all()
    {
        $rule = [
            'page' => 'integer|egt:1',
        ];
        $msg = [
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为1',
        ];

        $all = input('post.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $page = isset($all['page']) ? $all['page'] : 1;
		$search = isset($all['search']) ? $all['search'] : '';

        $perPage = 10;
        $offset = ($page - 1) * $perPage;

        $where['pay_money'] = ['>', 0];
		if (strlen($search) > 0) {
            $where['ord_num'] = ['like', '%' . $search . '%'];
        }

        $list = Order::where($where)
            ->field('id, type, source, real_money, pay_money, status, ord_num, add_time, checkstatus')
            ->order('id desc')
            ->limit($offset, $perPage)
            ->select();
        if (count($list) > 0) {
            foreach ($list as $k => $v) {
                $id = $v['id'];
                $checkstatus = $v['checkstatus'];
                if ($checkstatus == 0) {
                    $status = $v['status'];
                    $ord_num = $v['ord_num'];

                    $check = 0;
                    $result = 0;

                    $wxPay = new WxPay();
                    $appWxResult = $wxPay->AppWxAudit($ord_num);
                    if ($appWxResult['return_code'] == 'SUCCESS' && $appWxResult['result_code'] == 'SUCCESS' && $appWxResult['trade_state'] == 'SUCCESS') {
                        $check = 1;
                    }

                    $htmlWxResult = $wxPay->H5WxAudit($ord_num);
                    if ($htmlWxResult['return_code'] == 'SUCCESS' && $htmlWxResult['result_code'] == 'SUCCESS' && $htmlWxResult['trade_state'] == 'SUCCESS') {
                        $check = 1;
                    }

                    $alipay = new Alipay();
                    $appAlipayResult = $alipay->doQuery($ord_num);
                    if ($appAlipayResult->code == 10000 && ($appAlipayResult->trade_status == 'TRADE_SUCCESS' || $appAlipayResult->trade_status == 'TRADE_FINISHED')) {
                        $check = 1;
                    }

                    if ($check == 1) {
                        if ($status > 1) {
                            $result = 1;
                        } else {
                            $result = 4;
                        }
                    } else {
                        if ($status > 1) {
                            $result = 3;
                        } else {
                            $result = 2;
                        }
                    }

                    Order::where('id', '=', $id)->update(['checkstatus' => $result]);

                    $list[$k]['checkstatus'] = $result;
                }

                $list[$k]['add_time'] = date('Y-m-d H:i:s', $list[$k]['add_time']);
            }
        }

        return Utils::ajaxReturn(0, '查询成功', $list);
    }
	
	/*
     * 店铺列表
     */
    public function store()
    {
		$rule = [
            'page' => 'integer|egt:1',
        ];
        $msg = [
            'page.integer' => '页数为数字',
            'page.egt' => '页数最小为1',
        ];

        $all = input('post.');

        $validate = new Validate($rule, $msg);
        if (!$validate->check($all)) {
            $error = $validate->getError();

            return Utils::ajaxReturn(1, $error, null);
        }

        $page = isset($all['page']) ? $all['page'] : 1;
		$search = isset($all['search']) ? $all['search'] : '';

        $perPage = 10;
        $offset = ($page - 1) * $perPage;

        $where['is_del'] = 1;
		if (strlen($search) > 0) {
            $where['store_name'] = ['like', '%' . $search . '%'];
        }

        $list = Store::where($where)
            ->field('id, store_name')
            ->order('id desc')
			->limit($offset, $perPage)
            ->select();
		if (count($list) > 0) {
			foreach ($list as $k => $v) {
				$store_id = $v['id'];

                $orderMoney = 0.00;
                $flowMoney = 0.00;
                $withdrawMoney = 0.00;

                //店铺余额
                $storeRow = Store::where('id', '=', $store_id)
                    ->field('money, refund_money,kkm_money')
                    ->find();
                $money = $storeRow['money'];
                $refund_money = $storeRow['refund_money'];
                $kkm_money = $storeRow['kkm_money'];

                //订单
                $orderList = Order::where('store_id', '=', $store_id)
                    ->where('status', '>', 1)
                    ->where('ordtype', 'in', '1,3,4,5,6,7')
                    ->order('pay_time desc')
                    ->field('pay_money')
                    ->select();
                if (count($orderList) > 0) {
                    foreach ($orderList as $value) {
                        $orderMoney = bcadd($orderMoney, $value['pay_money'], 2);
                    }
                }

                //流水
                $flowList = Moneyflow::where('type', '=', 1)
                    ->where('pro_type', '<>', 7)
                    ->where('store_id', '=', $store_id)
                    ->where('is_error', '=', 0)
                    ->order('add_time desc')
                    ->field('money,kkm_money')
                    ->select();
                if (count($flowList) > 0) {
                    foreach ($flowList as $value) {
                        $flowMoney = bcadd($flowMoney, $value['money'], 2);
                        $flowMoney = bcadd($flowMoney, $value['kkm_money'], 2);
                    }
                }

                //提现
                $withdrawList = Withdraw::where('store_id', '=', $store_id)
                    ->field('money, poundage')
                    ->order('ctime desc')
                    ->select();
                if (count($withdrawList) > 0) {
                    foreach ($withdrawList as $value) {
                        $withdrawMoney = bcadd($withdrawMoney, $value['money'], 2);
                        $withdrawMoney = bcadd($withdrawMoney, $value['poundage'], 2);
                    }
                }

                $realMoney = bcadd($withdrawMoney, $money, 2);
                $realMoney = bcadd($realMoney, $kkm_money, 2);
                $realMoney = bcsub($realMoney, $refund_money, 2);
                if (bcsub($realMoney, $orderMoney, 2) > 0.00) {
                    $realStatus = 1;
                } else {
                    $realStatus = 2;
                }

                if (bcsub($flowMoney, $orderMoney, 2) > 0.00) {
                    $flowStatus = 1;
                } else {
                    $flowStatus = 2;
                }

                if ($realStatus == 2 && $flowStatus == 2) {
                    $list[$k]['status'] = 2;
                } else {
                    $list[$k]['status'] = 1;
                }

                $list[$k]['orderMoney'] = $orderMoney;
                $list[$k]['flowMoney'] = $flowMoney;
                $list[$k]['withdrawMoney'] = bcsub($withdrawMoney, $refund_money, 2);
                $list[$k]['money'] = $money;
                $list[$k]['kkmmoney'] = $kkm_money;
			}
		}

        return Utils::ajaxReturn(0, '查询成功', $list);
    }

}